#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_AVAILABLE_PATH/config/functions"

trigger-builder-dockerfile-builder-build() {
  declare desc="builder-dockerfile builder-build plugin trigger"
  declare trigger="builder-build"
  declare BUILDER_TYPE="$1" APP="$2" SOURCECODE_WORK_DIR="$3"

  if [[ "$BUILDER_TYPE" != "dockerfile" ]]; then
    return
  fi

  local IMAGE=$(get_app_image_name "$APP")
  local DOCKER_BUILD_LABEL_ARGS="--label=org.label-schema.schema-version=1.0 --label=org.label-schema.vendor=dokku --label=com.dokku.app-name=$APP"

  pushd "$SOURCECODE_WORK_DIR" &>/dev/null

  # extract first port from Dockerfile
  local DOCKERFILE_PORTS=$(get_dockerfile_exposed_ports Dockerfile)
  [[ -n "$DOCKERFILE_PORTS" ]] && config_set --no-restart "$APP" DOKKU_DOCKERFILE_PORTS="$DOCKERFILE_PORTS"

  # extract ENTRYPOINT/CMD from Dockerfile
  local DOCKERFILE_ENTRYPOINT=$(extract_directive_from_dockerfile Dockerfile ENTRYPOINT)
  [[ -n "$DOCKERFILE_ENTRYPOINT" ]] && config_set --no-restart "$APP" DOKKU_DOCKERFILE_ENTRYPOINT="$DOCKERFILE_ENTRYPOINT"
  local DOCKERFILE_CMD=$(extract_directive_from_dockerfile Dockerfile CMD)
  [[ -n "$DOCKERFILE_CMD" ]] && config_set --no-restart "$APP" DOKKU_DOCKERFILE_CMD="$DOCKERFILE_CMD"
  plugn trigger pre-build-dockerfile "$APP"

  [[ "$DOKKU_DOCKERFILE_CACHE_BUILD" == "false" ]] && DOKKU_DOCKER_BUILD_OPTS="$DOKKU_DOCKER_BUILD_OPTS --no-cache"
  local DOCKER_ARGS=$(: | plugn trigger docker-args-build "$APP" "$BUILDER_TYPE")
  DOCKER_ARGS+=$(: | plugn trigger docker-args-process-build "$APP" "$BUILDER_TYPE")

  # strip --volume and -v args from DOCKER_ARGS
  local DOCKER_ARGS=$(sed -e "s/--volume=[[:graph:]]\+[[:blank:]]\?//g" -e "s/-v[[:blank:]]\?[[:graph:]]\+[[:blank:]]\?//g" <<<"$DOCKER_ARGS")
  declare -a ARG_ARRAY
  eval "ARG_ARRAY=($DOCKER_ARGS)"

  "$DOCKER_BIN" image build "${DOCKER_BUILD_LABEL_ARGS[@]}" $DOKKU_GLOBAL_BUILD_ARGS "${ARG_ARRAY[@]}" "${DOKKU_DOCKER_BUILD_OPTS[@]}" -t $IMAGE .

  plugn trigger post-build-dockerfile "$APP"
}

trigger-builder-dockerfile-builder-build "$@"
